package com.idbk.chargestation.activity.assist;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.idbk.chargestation.MainActivity;
import com.idbk.chargestation.R;

/**
 * 浏览器
 * @author lupc
 *
 */
public class ActivityBrowser extends Activity implements OnClickListener {

	public final static String KEY_URL = "key_url";
	
	public final static String KEY_TITLE = "key_title";
	
	public final static String KEY_IS_TO_MAIN = "key_is_to_main";
	
	private boolean mIsToMain = false;
	
	private WebView mWebView;

	private TextView mTextTitle;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_browser);

		setupView();

		setupData();
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void setupView() {
		findViewById(R.id.toolbar_back).setOnClickListener(this);
		mTextTitle = (TextView)findViewById(R.id.toolbar_title);
		mWebView = (WebView)findViewById(R.id.webview);
		//启用javascript
		mWebView.getSettings().setJavaScriptEnabled(true);
		//
		mWebView.setWebViewClient(new WebViewClient(){

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}
			
		});
	}

	private void setupData(){
		String url = getIntent().getStringExtra(KEY_URL);		
		if(url == null){
			finish();
		} else {
			mWebView.loadUrl(url);
		}
		String title = getIntent().getStringExtra(KEY_TITLE);
		if(title != null){
			mTextTitle.setText(title);
		}
		mIsToMain = getIntent().getBooleanExtra(KEY_IS_TO_MAIN, false);
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.toolbar_back){
			if(mIsToMain){
				Intent intent = new Intent(ActivityBrowser.this, MainActivity.class);
				startActivity(intent);
				finish();
			} else {
				finish();
			}			
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()){
			mWebView.goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
